"""
OpenAI内容生成器
"""

from openai import AsyncOpenAI
from typing import Dict, Any
import json

from .base import BaseGenerator
from ..core.config import get_settings
from ..core.logger import app_logger

settings = get_settings()


class OpenAIGenerator(BaseGenerator):
    """基于OpenAI的内容生成器"""
    
    def __init__(self):
        super().__init__()
        if settings.OPENAI_API_KEY and settings.OPENAI_API_KEY != "your_openai_api_key_here":
            # 修复：避免传递可能引起冲突的参数
            try:
                self.client = AsyncOpenAI(api_key=settings.OPENAI_API_KEY)
            except TypeError as e:
                # 如果出现参数错误，尝试不带任何额外参数初始化
                if "proxies" in str(e):
                    self.client = AsyncOpenAI(api_key=settings.OPENAI_API_KEY, http_client=None)
                else:
                    raise e
        else:
            self.client = None
            app_logger.warning("未设置OpenAI API密钥")
    
    async def generate(self, trend_data: Dict[str, Any], platform: str, style: str = "default") -> Dict[str, Any]:
        """使用OpenAI生成内容"""
        
        if not self.client:
            # 返回模拟内容
            return await self._generate_mock_content(trend_data, platform, style)
        
        try:
            prompt = self._build_prompt(trend_data, platform, style)
            
            response = await self.client.chat.completions.create(
                model=settings.OPENAI_MODEL or "gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "你是一个专业的社交媒体内容创作者。"},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=300,
                temperature=0.7
            )
            
            content = response.choices[0].message.content.strip()
            
            # 检查敏感内容
            if not self.filter_sensitive_content(content):
                app_logger.warning("生成的内容包含敏感词，使用默认内容")
                return await self._generate_fallback_content(trend_data, platform)
            
            # 格式化内容
            formatted = self.format_for_platform(content, platform)
            
            # 提取话题标签
            hashtags = self._extract_hashtags(content, platform)
            
            return {
                "text": formatted["content"],
                "hashtags": hashtags,
                "platform": platform,
                "style": style,
                "source": "openai"
            }
            
        except Exception as e:
            app_logger.error(f"OpenAI生成内容失败: {e}")
            return await self._generate_fallback_content(trend_data, platform)
    
    def _build_prompt(self, trend_data: Dict[str, Any], platform: str, style: str) -> str:
        """构建提示词"""
        
        platform_prompts = {
            "weibo": "请为微博平台创作一条推文",
            "twitter": "请为Twitter平台创作一条推文",
            "wechat": "请为微信公众号创作一段内容"
        }
        
        style_prompts = {
            "default": "保持中性和客观的语调",
            "formal": "使用正式和专业的语调",
            "casual": "使用轻松和亲民的语调",
            "humorous": "可以适当加入幽默元素"
        }
        
        prompt = f"""
{platform_prompts.get(platform, platform_prompts['weibo'])}，{style_prompts.get(style, style_prompts['default'])}。

热点信息：
标题：{trend_data['title']}
描述：{trend_data.get('description', '')}
来源：{trend_data.get('source', '')}

要求：
1. 内容要有吸引力和话题性
2. 适合{platform}平台的用户群体
3. 包含相关的话题标签
4. 避免敏感内容
5. 保持内容的原创性

请直接返回推文内容，不需要额外说明。
"""
        
        return prompt.strip()
    
    def _extract_hashtags(self, content: str, platform: str) -> str:
        """提取或生成话题标签"""
        
        # 从内容中提取现有标签
        import re
        
        if platform == "weibo":
            hashtags = re.findall(r'#([^#]+)#', content)
        else:
            hashtags = re.findall(r'#(\w+)', content)
        
        # 如果没有标签，生成默认标签
        if not hashtags:
            default_tags = ["热点", "AI推荐", "今日话题"]
            hashtags = default_tags[:2]
        
        if platform == "weibo":
            return " ".join([f"#{tag}#" for tag in hashtags])
        else:
            return " ".join([f"#{tag}" for tag in hashtags])
    
    async def _generate_mock_content(self, trend_data: Dict[str, Any], platform: str, style: str) -> Dict[str, Any]:
        """生成模拟内容（用于测试）"""
        
        title = trend_data["title"]
        description = trend_data.get("description", "")
        
        mock_templates = {
            "weibo": {
                "default": f"🔥 {title}\n\n{description[:50]}{'...' if len(description) > 50 else ''}\n\n这个话题很有意思，大家怎么看？ #热点话题# #AI推荐#",
                "formal": f"【关注】{title}\n\n{description[:80]}{'...' if len(description) > 80 else ''}\n\n值得深入了解。#热点资讯#",
                "casual": f"哇！{title} 🎉\n\n{description[:60]}{'...' if len(description) > 60 else ''}\n\n你们觉得呢？ #今日热点# #讨论#"
            },
            "twitter": {
                "default": f"🚀 {title}\n\n{description[:100]}{'...' if len(description) > 100 else ''}\n\n#trending #news",
                "formal": f"Breaking: {title}\n\n{description[:120]}{'...' if len(description) > 120 else ''}\n\n#breaking #update",
                "casual": f"Wow! {title} ✨\n\n{description[:80]}{'...' if len(description) > 80 else ''}\n\nThoughts? #viral #discussion"
            },
            "wechat": {
                "default": f"【今日关注】{title}\n\n{description}\n\n这一热点话题引起了广泛关注，反映了当前社会的关注焦点。我们将持续跟踪相关动态，为大家带来最新资讯。",
                "formal": f"【深度解读】{title}\n\n{description}\n\n从专业角度分析，这一事件具有重要意义，值得我们深入思考和讨论。",
                "casual": f"【热点分享】{title}\n\n{description}\n\n今天这个话题挺有意思的，和大家分享一下我的看法..."
            }
        }
        
        template = mock_templates.get(platform, mock_templates["weibo"]).get(style, mock_templates[platform]["default"])
        
        # 格式化内容
        formatted = self.format_for_platform(template, platform)
        
        # 生成标签
        hashtags = self._extract_hashtags(template, platform)
        
        return {
            "text": formatted["content"],
            "hashtags": hashtags,
            "platform": platform,
            "style": style,
            "source": "mock"
        }
    
    async def _generate_fallback_content(self, trend_data: Dict[str, Any], platform: str) -> Dict[str, Any]:
        """生成备用内容"""
        return await self._generate_mock_content(trend_data, platform, "default")